// import { asyncRouterMap, constantRouterMap } from '@/router'
import constantRouterMap from '@/router/const_router'
import asyncRouterMap from '@/router/async_router'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param rules
 * @param route
 */
function hasPermission(rules, route) {
  if (route.meta && route.meta.auth) {
    return rules.indexOf(route.name) >= 0
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param rules
 */
function filterAsyncRouter(asyncRouterMap, rules) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(rules, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, rules)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

function removeTempMenu(routers, views) {
  const data = []
  for (const router of routers) {
    if (router.children && router.children.length) {
      const children = removeTempMenu(router.children, views)
      if (children.length < router.children.length) {
        router.children = children
      }
    }
    if (!router.temp) {
      data.push(router)
      continue
    } else {
      if (router.children && router.children.length) {
        data.push(router)
        continue
      }
      for (const item of views) {
        if (router.name === item.name) {
          data.push(router)
          break
        }
      }
    }
  }
  return data
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    // 添加临时模板到子菜单
    SET_MENU_ROUTE: (state, { submenus, parent }) => {
      for (let i = 0, len = state.routers.length; i < len; i++) {
        if (state.routers[i].name === parent) {
          const children = state.routers[i].children.filter(item => {
            return !item.temp
          })
          children.push(submenus)
          state.routers[i].children = children
          break
        }
      }
    },
    // 移除临时菜单
    DEL_TEMP_MENU: (state, views) => {
      state.routers = removeTempMenu(state.routers, views)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { rules } = data
        const accessedRouters = filterAsyncRouter(asyncRouterMap, rules)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    },
    AddSubMenus({ commit }, { submenus, parent }) {
      return new Promise(resolve => {
        commit('SET_MENU_ROUTE', { submenus, parent })
        resolve()
      })
    },
    DelTempMenus({ commit }, views) {
      return new Promise(resolve => {
        commit('DEL_TEMP_MENU', views)
        resolve()
      })
    }
  }
}

export default permission
